<template>
  <div class="addAddress">
    <ContentBox title="新建地址" @left="back" :fixed="true">
      <template slot="oleft"><van-icon color="#000000" name="arrow-left"/></template>
    </ContentBox>
    <notice :top="$remToPx('0.88')"></notice>
    <van-address-edit
      class="addressForm"
      :area-list="areaList"
      show-set-default
      show-search-result
      :address-info="AddressInfo"
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @change-area="getCode"
    />
  </div>
</template>

<script>
import area from '@/assets/js/area.js'
export default {
  data () {
    return {
      areaList: '',
      searchResult: [],
      AddressInfo: {},
      code: ''
    }
  },
  methods: {
    back () {
      this.$router.go(-1)
    },
    getCode (val) {
      this.code = val[2].code
    },
    onSave (content) {
      this.$axios.post('/api/address/edit', {
        real_name: content.name,
        phone: content.tel,
        detail: content.addressDetail,
        is_default: content.isDefault ? 1 : 0,
        address: {
          province: content.province,
          city: content.city,
          district: content.county
        },
        id: this.$route.query.index > -1 ? this.AddressInfo.id : 0,
        code: this.code
      }).then(res => {
        if (res.status === 200) {
          this.$dialog({ message: '添加成功' })
          if (this.$route.query.id && this.$route.query.orderKey) {
            this.$router.replace({ name: 'myAddress', query: { id: this.$route.query.id, orderKey: this.$route.query.orderKey } })
          } else {
            this.$router.replace('/myAddress')
          }
        }
      })
    },
    getListIndexData () {
      this.$axios.get('/api/address/list').then(res => {
        if (res.status === 200) {
          this.AddressInfo = {
            name: res.data[this.$route.query.index].real_name,
            tel: res.data[this.$route.query.index].phone,
            addressDetail: res.data[this.$route.query.index].detail,
            isDefault: res.data[this.$route.query.index].is_default ? true : 0,
            province: res.data[this.$route.query.index].province,
            city: res.data[this.$route.query.index].city,
            county: res.data[this.$route.query.index].district,
            id: res.data[this.$route.query.index].id,
            areaCode: res.data[this.$route.query.index].code
          }
        }
      })
    }
  },
  created () {
    this.areaList = area
    if (this.$route.query.index > -1) {
      this.getListIndexData()
    }
  }
}
</script>

<style lang="scss">
.addAddress{
  .addressForm{
    padding-top: 1.36rem;
  }
}
</style>
